package com.cd.music.utils;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yxl 余秀良
 * @version 1.0
 * @description: 用于后端向页面返回数据
 * @date 2017年10月25日 上午11:37
 * @address: 四川成都
 */
public final class ServletUtil {
    private static final Logger logger = Logger.getLogger(ServletUtil.class);

    /**
     * @description:
     * @author yxl  余秀良
     * @date 17-10-25 上午11:47
     * @address: 四川成都
     */
    public static void returnJson(HttpServletResponse response, Object result, String message, boolean success, int code) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //设置跨域请求
        response.addHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultMap = new HashMap<>(16);
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("data", result);
        dataMap.put("success", success);
        dataMap.put("code", code);
        dataMap.put("message", message);
        resultMap.put("response", dataMap);
        result(response, resultMap);
        dataMap.clear();
    }

    public static void returnJson(HttpServletResponse response, Object result, String message) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //设置跨域请求
        response.addHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> resultMap = new HashMap<>(16);
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("data", result);
        dataMap.put("message", message);
        resultMap.put("response", dataMap);
        result(response, resultMap);
        dataMap.clear();
    }

    /**
     * @description:
     * @author yxl  余秀良
     * @date 17-10-25 上午11:47
     * @address: 四川成都
     */
    private static void result(HttpServletResponse response, Map<String, Object> map) {
        try {
            //得到PrintWriter
            PrintWriter writer = response.getWriter();
            //转为json
            String json = JSON.toJSONString(map);
            writer.print(json);
            //关闭PrintWriter
            writer.close();
            //清空Map
            map.clear();
        } catch (IOException e) {
            logger.error("ServletUtil类的result方法报错" + e.getMessage());
            e.printStackTrace();
        }
    }
}
